const app = getApp();
const util = require('../../../utils/util.js');
const lbbService = require('../../../pages/service/service.js');
const lbbTaskService = require('../service/task-service.js');
const operateMethod =require('../service/operatef.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        friendlyCollectList: [{
            text: '采集到',
            value: 1
        }, {
            text: '未采集到',
            value: 0
        }],
        friendlyCollect: 1,
        friendlyInfo: [{
            contactList: []
        }],
        friendlyBusList: [],
        hasFriendlyAgent: 1,
        friendlyAgentName: '',
        showContacts: false,
        contactObj: {},
        contactTypeList: [],
        onBeforeClose(action, done) {
            if (action == 'confirm') {
                return false
            } else {
                return true
            }
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
   async onLoad(options) {
        let that = this
        that.setData({
            taskId: options.taskId,
            hospitalId: options.hospitalId,
            taskType:options.taskType,
            operationlist : options.operationlist?JSON.parse(options.operationlist):[],
            operationTypeCode:options.operationTypeCode,
            activeKey:options.activeKey
        })
       await that.getDetailById()
       await that.getProjectList('friendly_business')
       await that.getProjectList('contact_information')
       await that.getCollectFriendly()
    },
    //获取任务详情
    getDetailById() {
        let that = this
        lbbTaskService.getDetailById({
            taskId: that.data.taskId
        }, function (res) {
            if (res.data) {
                that.setData({
                    taskProjectText: res.data.taskProjectText,
                    taskClassificationName: res.data.taskClassificationName,
                    hospitalName: res.data.hospitalName,
                    taskDesc: res.data.taskDesc,
                    taskImages: res.data.taskImages ? res.data.taskImages.split(',') : [],
                    isUrgent: res.data.isUrgent
                })
            }
        })
    },
    //获取数据字典值
    getProjectList(code) {
        let that = this
        lbbTaskService.getDictByCode({
            code: code
        }, function (res) {
            if (code == 'friendly_business') {
                that.setData({
                    friendlyBusList: res.data
                })
            } else if (code == 'contact_information') {
                that.setData({
                    contactTypeList: res.data
                })
            }
        })
    },
    //信息回显
    getCollectFriendly(){
        let that=this
        lbbTaskService.getCollectFriendly({taskId:that.data.taskId},function(res) {
            if(res.data){
                if(res.data.friendlyInfo.length==0||!res.data.friendlyInfo){
                    res.data.friendlyInfo=[{contactList:[]}]
                }else{
                    res.data.friendlyInfo.forEach(item=>{
                        if(!item.contactList||item.contactList?.length==0){
                            item.contactList=[]
                        }else{
                            item.contactList.forEach(itemy=>{
                                itemy.contactTypeText=that.data.contactTypeList.find(itm=>itm.value==itemy.contactType).text
                            })
                        }
                        item.friendlyBusinessText=that.data.friendlyBusList.find(itm=>itm.value==item.friendlyBusiness).text
                        item.images=item.images?item.images.split(','):''
                    })
                }
                that.setData({
                    friendlyCollect:res.data.friendlyCollect,
                    friendlyInfo:res.data.friendlyInfo
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },
    //友商说标人信息选择
    onChangeCollect(e) {
        this.setData({
            friendlyCollect: e.detail
        })
    },
    //打开友商公司选择
    onBindFriendlyBus(e) {
        console.log(e)
        this.setData({
            friendlyBusIfShow: true,
            listIndex: e.currentTarget.dataset.index
        })
    },
    //选择友商公司的回调
    okFriendlyBus(e) {
        this.data.friendlyInfo[this.data.listIndex].friendlyBusiness = e.detail.id
        this.data.friendlyInfo[this.data.listIndex].friendlyBusinessText = e.detail.name
        this.setData({
            friendlyBusIfShow: false,
            friendlyInfo: this.data.friendlyInfo
        })
    },
    //有无代理商
    onChangeHasRadio(e) {
        this.data.friendlyInfo[e.currentTarget.dataset.index].hasFriendlyAgent = e.detail
        this.setData({
            friendlyInfo: this.data.friendlyInfo
        })
    },
    //代理商名称
    onChangeAgentName(e) {
        this.data.friendlyInfo[e.currentTarget.dataset.index].friendlyAgentName = e.detail
        this.setData({
            friendlyInfo: this.data.friendlyInfo
        })
    },
    //新增联系人
    addContacts(e) {
        console.log(e)
        this.setData({
            showContacts: true,
            listIndex: e.currentTarget.dataset.index
        })
    },
    //联系人姓名回调
    onChangeName(e) {
        this.data.contactObj.name = e.detail
        this.setData({
            contactObj: this.data.contactObj
        })
    },
    //打开联系方式列表
    onBindcontactType(e) {
        this.setData({
            contactTypeIfShow: true
        })
    },
    //选择联系方式
    okContactType(e) {
        this.data.contactObj.contactTypeText = e.detail.name
        this.data.contactObj.contactType = e.detail.id
        this.setData({
            contactTypeIfShow: false,
            contactObj: this.data.contactObj
        })
    },
    //联系号码回调
    onChangecontactWay(e) {
        this.data.contactObj.contactWay = e.detail
        this.setData({
            contactObj: this.data.contactObj
        })
    },
    //联系人职务
    onChangeposition(e) {
        this.data.contactObj.position = e.detail
        this.setData({
            contactObj: this.data.contactObj
        })
    },
    //确定新增联系人
    onConfirmContacts() {
        if (this.data.contactObj.name && this.data.contactObj.contactType && this.data.contactObj.contactWay && this.data.contactObj.position) {
            this.data.friendlyInfo[this.data.listIndex].contactList.push(this.data.contactObj)
            this.setData({
                showContacts: false,
                friendlyInfo: this.data.friendlyInfo,
                contactObj: {}
            })
            console.log(33, this.data.friendlyInfo)
        } else {
            this.openPrompt()
        }
    },
    //关闭联系人弹框
    onCloseContacts() {
        this.setData({
            contactObj: {}
        })
    },
    //删除联系人
    delContacterBox(e) {
        console.log(e)
        this.data.friendlyInfo[e.currentTarget.dataset.index].contactList.splice(e.currentTarget.dataset.indext, 1)
        this.setData({
            friendlyInfo: this.data.friendlyInfo
        })
    },
    //备注
    changeRemark(e) {
        this.data.friendlyInfo[e.currentTarget.dataset.index].remark = e.detail.value
        this.setData({
            friendlyInfo: this.data.friendlyInfo
        })
    },
    //图片上传
    setImgArr(e) {
        let that = this
        let imgArray = e.detail;
        let newUpLoadImg = []
        let oldUpLoadImg = []
        imgArray.forEach(item => {
            if (item.indexOf('http://tmp/') != -1||item.indexOf('wxfile://tmp')!=-1) {
                newUpLoadImg.push(item)
            } else {
                oldUpLoadImg.push(item)
            }
        })
        wx.showLoading({
            title: '正在上传图片',
            mask: true
        })
        util.newUpLoadImg(app.globalData.header, newUpLoadImg, 0, [], function (imgIdArray) {
            console.log('item================>', imgIdArray)
            wx.hideLoading()
            oldUpLoadImg.push(...imgIdArray)
            that.data.friendlyInfo[e.currentTarget.dataset.index].images = oldUpLoadImg
        });
    },
    //删除友商
    delTask(e) {
        this.data.friendlyInfo.splice(e.currentTarget.dataset.index, 1)
        this.setData({
            friendlyInfo: this.data.friendlyInfo
        })
    },
    //添加友商
    addFriendlyInfo() {
        this.data.friendlyInfo.push({
            contactList: []
        })
        this.setData({
            friendlyInfo: this.data.friendlyInfo
        })
    },
    //提交
    btnSubmit() {
        let that=this
        if (this.data.friendlyCollect == 1) {
            let checkList=[]
            let obj={}
            this.data.friendlyInfo.forEach(item=>{
                item.images=item.images?item.images.toString():''
                item.remark=item.remark?item.remark:''
                if(item.friendlyBusiness){
                    checkList.push(1)
                }else{
                    checkList.push(0)
                }
                if(item.hasFriendlyAgent!=0&&item.hasFriendlyAgent!=1){
                    checkList.push(0)
                }else{
                    checkList.push(1)
                }
                if(item.hasFriendlyAgent==0){
                    item.contactList=[]
                    item.friendlyAgentName=''
                }else if(item.hasFriendlyAgent==1){
                    if(!item.friendlyAgentName){
                        checkList.push(0)  
                    }else{
                        checkList.push(1)
                    }
                }
            })
            obj={friendlyCollect:that.data.friendlyCollect,friendlyInfo:that.data.friendlyInfo,taskId:that.data.taskId}
            if(checkList.indexOf(0)!=-1){
                that.openPrompt()
            }else{
                that.postCollectFriendly(JSON.stringify(obj))
            }
        } else {
            that.postCollectFriendly(JSON.stringify({friendlyCollect:that.data.friendlyCollect,friendlyInfo:[],taskId:that.data.taskId}))
        }
    },
    //提交接口
    postCollectFriendly(params){
        let that= this
        lbbTaskService.collectFriendly({friendlyInfo:params},function(res) {
            if (that.data.activeKey == 3) {
                wx.navigateBack({
                    delta: 1
                })
            } else {
                operateMethod(that.data.operationlist, that.data.taskId, that.data.hospitalId, that.data.taskType, that.data.operationTypeCode)
            }
        })
    },
    //校验提示
    openPrompt() {
        wx.showToast({
            title: '请检查必填项',
            icon: 'error',
            duration: 2000
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})